import 'element-ui/lib/theme-chalk/index.css';
<template>
  <div class="boxs">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="决策树名称" prop="jcs_name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable size="small" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button><el-button
          icon="el-icon-plus" type="primary" plain size="small" @click="openDialog">新建决策树项目</el-button>
      </el-form-item>
    </el-form>


    <el-table :data="jcsArr" style="width: 100%" v-loading="loading">
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="决策树名称" align="center" prop="jcs_name" />
      <el-table-column label="决策树描述" align="center" prop="jcs_info" />
      <el-table-column label="创建时间" align="center" prop="create_time" />
      <el-table-column label="操作" align="center" width="350">
        <template slot-scope="scope">
          <el-button size="mini" v-if="scope.row.admin !== 1"
            @click="handleJcsIndex(scope.$index, scope.row)">查看决策树</el-button>
          <el-button size="mini" v-if="scope.row.admin !== 1" type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>

      <el-table-column prop="bllx" v-if="false" />
      <el-table-column prop="ssbz" v-if="false" />
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.size"
      @pagination="getJcsList" />


    <el-dialog title="新建决策树(根节点)" :visible.sync="dialogVisible" width="60%">
      <el-form class="demo-form-inline" label-width="80px" :model="form" :rules="addrules" ref="ruleForm">
        <el-form-item label="决策树名称" prop="jcs_name">
          <el-input v-model="form.jcs_name" placeholder="决策树名称" />
        </el-form-item>

        <el-form-item label="决策树描述" prop="jcs_info">
          <el-input v-model="form.jcs_info" placeholder="决策树描述">
          </el-input>
        </el-form-item>
        <el-form-item label="节点名称" prop="name">
          <el-input v-model="form.name" placeholder="节点名称，如“步骤一”">
          </el-input>
        </el-form-item>

        <el-form-item label="报警类型" prop="alarmIds">
          <el-select v-model="form.alarmIds" filterable placeholder="请选择报警类型" multiple>
            <el-option v-for="item in alarmArr" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="故障类型" prop="faultIds">
          <el-select v-model="form.faultIds" filterable placeholder="请选择故障类型" multiple>
            <el-option v-for="item in faultArr" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否叶子节点">
          <el-radio-group v-model="form.is_leaf">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="详细步骤">
          <quill-editor ref="text" v-model="form.detail" class="myQuillEditor" />
        </el-form-item>

        <el-form-item label="图片上传">
          <el-upload name="images" ref="upload" class="upload-demo" action="" list-type="picture-card"
            :file-list="fileList" :on-preview="handlePreview" :on-remove="handleRemove" :on-change="handleChange"
            :before-upload="beforeUpload" :auto-upload="false">
            <i class="el-icon-plus"></i> <!-- 上传按钮 -->
          </el-upload>

          <!-- 图片预览 -->
          <el-dialog :visible.sync="previewDialogVisible">
            <img width="100%" :src="previewImage" alt="preview" />
          </el-dialog>
        </el-form-item>


      </el-form>

      <div slot="footer" class="dialog-footer" v-loading="addLoading">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :type="form.id ? 'warning' : 'primary'" @click="add">添加</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑决策树" :visible.sync="editDialogVisible" width="50%">
      <el-form class="demo-form-inline" label-width="80px" :model="editForm" :rules="addrules" ref="ruleForm">

        <el-form-item label="节点名称" prop="name">
          <el-input v-model="editForm.name" placeholder="节点名称，如“步骤一”">
          </el-input>
        </el-form-item>

        <el-form-item v-show="editForm.parent_id != -1" label="按钮名称" prop="node_text">
          <el-input v-model="editForm.node_text" placeholder="按钮名称，即上一个节点点击的按钮">
          </el-input>
        </el-form-item>

        <el-form-item label="是否叶子节点">
          <el-radio-group v-model="editForm.is_leaf">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="详细步骤">
          <quill-editor ref="text" v-model="editForm.detail" class="myQuillEditor" />
        </el-form-item>

        <el-form-item label="图片列表">
          <!-- 图片列表 -->
          <el-row :gutter="20">
            <el-col :span="6" v-for="(img, index) in imageList" :key="img.id">
              <div class="image-card">
                <img :src="baseurl + img.url" alt="图片" style="width: 100%; height: auto;" />
                <el-button size="mini" type="danger" @click="deleteImage(img, index)">
                  删除
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="图片上传">
          <el-upload name="images" ref="upload" class="upload-demo" action="" list-type="picture-card"
            :file-list="fileList" :on-preview="handlePreview" :on-remove="handleRemove" :on-change="handleChange"
            :before-upload="beforeUpload" :auto-upload="false">
            <i class="el-icon-plus"></i> <!-- 上传按钮 -->
          </el-upload>

          <!-- 图片预览 -->
          <el-dialog :visible.sync="previewDialogVisible">
            <img width="100%" :src="previewImage" alt="preview" />
          </el-dialog>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer" v-loading="editNodeLoading">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="delNode(editForm.id)">删除子节点</el-button>
        <el-button type="primary" @click="openInsertDialog(editForm.id)">插入子节点</el-button>
        <el-button type="primary" @click="editJcsNode">保存编辑</el-button>
      </div>
    </el-dialog>

    <el-dialog title="插入子节点" :visible.sync="insertDialogVisible" width="45%">
      <el-form class="demo-form-inline" label-width="80px" :model="insertform" :rules="insertrules"
        ref="insertruleForm">

        <el-form-item label="节点名称" prop="name">
          <el-input v-model="insertform.name" placeholder="节点名称，如“步骤一”">
          </el-input>
        </el-form-item>

        <el-form-item label="按钮名称" prop="node_text">
          <el-input v-model="insertform.node_text" placeholder="按钮名称">
          </el-input>
        </el-form-item>

        <el-form-item label="是否叶子节点">
          <el-radio-group v-model="insertform.is_leaf">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="详细步骤">
          <quill-editor ref="text" v-model="insertform.detail" class="myQuillEditor" />
        </el-form-item>

        <el-form-item label="图片上传">
          <el-upload name="images" ref="upload" class="upload-demo" action="" list-type="picture-card"
            :file-list="fileList" :on-preview="handlePreview" :on-remove="handleRemove" :on-change="handleChange"
            :before-upload="beforeUpload" :auto-upload="false">
            <i class="el-icon-plus"></i> <!-- 上传按钮 -->
          </el-upload>

          <!-- 图片预览 -->
          <el-dialog :visible.sync="previewDialogVisible">
            <img width="100%" :src="previewImage" alt="preview" />
          </el-dialog>
        </el-form-item>


      </el-form>

      <div slot="footer" class="dialog-footer" v-loading="insertNodeLoading">
        <el-button @click="insertDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleinsertJcsNode">插入</el-button>
      </div>
    </el-dialog>


    <el-dialog title="树形图编辑器" :visible.sync="jcsdialogVisible" width="60%">
      <TreeChart align="center" :json="treeData" @click-node="clickNode" />
    </el-dialog>


  </div>
</template>
<script>
import { getJcsList, getJcs, getJcsNode, upJcsNode, addJcs, insertJcsNode, upJcs, delJcs, getMoreAll, getRolesAll, getFaultList, getAlarmList, addPic, delPic } from '@/api/admin';
import { formatDate } from "@/utils";
// import md5 from 'js-md5';
import { quillEditor } from 'vue-quill-editor';
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import TreeChart from "vue-tree-chart";


export default {

  name: "User",
  data() {
    return {
      // editorContent: '', // 富文本内容绑定的数据
      queryParams: {
        page: 1,
        size: 10
      },
      // baseurl: 'http://localhost:8080/api/v1',
      baseurl: 'https://guide.hpaitech.cn/api/v1',
      // baseurl: 'https://guide.smart-park.nnweather.com/api/v1',
      fileList: [],
      total: 0,
      loading: false,
      addLoading: false,
      editNodeLoading: false,
      insertNodeLoading: false,
      jcsArr: [],
      dialogVisible: false,
      editDialogVisible: false,
      insertDialogVisible: false,
      themeOpen: false,
      rolesArr: [],
      moreArr: [],
      faultArr: [],
      alarmArr: [],
      bllxArr: [],
      statusArr: [],
      search: '',
      form: {
        rxbz: '',
        is_leaf: 0,
      },
      editForm: {

      },
      insertform: {
        is_leaf: 0,
      },
      addrules: {
        jcs_name: [
          { required: true, message: '请输入决策树名称', trigger: 'change' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        jcs_info: [
          { required: true, message: '请输入决策树详细信息', trigger: 'change' },
          { min: 1, max: 2000, message: '长度在 1 到 2000 个字符', trigger: 'blur' }
        ],

        name: [
          { required: true, message: '请输入根节点名称', trigger: 'change' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        faultIds: [
          { required: true, message: '请选择故障类型', trigger: 'blur' }
        ],
        alarmIds: [
          { required: true, message: '请选择报警类型', trigger: 'blur' }
        ],
      },
      insertrules: {
        name: [
          { required: true, message: '请输入根节点名称', trigger: 'change' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        node_text: [
          { required: true, message: '请输入按钮名称', trigger: 'change' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        is_leaf: [
          { required: true, message: '选择是否为叶子节点', trigger: 'change' },
        ],


      },
    
      previewImage: '',           // 当前预览的图片
      previewDialogVisible: false,  // 控制预览对话框


      // 决策树窗口变量
      curNode: null,
      jcsdialogVisible: false,
      treeData: {

      },
      imageList: [],  // 存储图片列表

    }
  },
  components: {
    quillEditor,
    TreeChart
  },
  async created() {
    await this.getFalut();
    await this.getAlarm();
    // await this.getSsbz();
    // await this.getBllx();
    this.getJcsList();
  },
  methods: {
    formatterCreateTime(row) {
      return formatDate(row.createTime);
    },
    formatMore(row) {
      if (row.admin === 1) return "总管理";
      let res = this.moreArr.filter(t => t.id == row.moreId);
      if (res.length == 0) return "“账号不存在”"
      return res[0].name
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该决策树, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        await delJcs({ id: row.id });
        this.getJcsList();
        this.$message({
          message: '删除成功！',
          type: 'success'
        });
      })
    },
    // 删除子节点
    delNode(nodeid) {
      this.$confirm('此操作将永久删除该子节点及以下的树, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        await delJcs({ id: nodeid });
        this.editDialogVisible = false;
        // 刷新决策树列表
        this.getJcsList();
        // 刷新树形图
        let res = await getJcs({ id: this.treeData.id });
        this.treeData = res.data;
        this.$message({
          message: '删除成功！',
          type: 'success'
        });
      })
    },
    resetForm() {
      this.form = { is_leaf: 0, };
    },
    // 打开决策树主页
    async handleJcsIndex(index, row) {
      // this.resetForm();
      console.log('index', index, 'row:', row);

      this.form = { ...row };
      // this.$set(this.form, "rolesId", row.rolesId.split(","));
      let res = await getJcs({ id: row.id });
      this.treeData = res.data;
      this.jcsdialogVisible = true;
    },

    // 添加决策树，即根节点
    async add() {
      try {

        this.addLoading = true;
        // let rolesId=this.form.rolesId.join(",");
        // this.form.id && await addJcs({ ...this.form });


        // 验证表单
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            try {
              const myjcs = await addJcs({ ...this.form });
              console.log('添加结果:', myjcs);
              if (myjcs.code == 1) {
                this.$message.success('添加成功！');

                // 只有当有文件需要上传时才执行上传操作
                if (this.fileList && this.fileList.length > 0) {
                  const formData = new FormData();

                  // 将文件添加到 FormData
                  this.fileList.forEach((file) => {
                    formData.append('images', file.raw); // file.raw 是原始文件
                  });

                  console.log('formData', formData);
                  formData.append('jcs_id', myjcs.data.insertId);
                  const r = await addPic(formData);
                  this.$message.success(r.msg);
                }
              } else {
                this.$message.error(`提交失败: ${myjcs.msg}`);
              }
            } catch (error) {
              console.error('提交出错:', error);
              this.$message.error('提交失败，请稍后再试');
            }

            this.addLoading = false;
            this.getJcsList();
            this.dialogVisible = false;
          } else {
            this.$message.error('请填写完整信息');
            this.addLoading = false;
          }
        });


      } catch (e) {
        this.addLoading = false;
      }

    },
    // 插入子节点
    async handleinsertJcsNode() {
      try {

        this.insertNodeLoading = true;
        // let rolesId=this.form.rolesId.join(",");
        // this.form.id && await addJcs({ ...this.form });


        // 验证表单
        this.$refs.insertruleForm.validate(async (valid) => {
          if (valid) {
            try {
              const myjcs = await insertJcsNode({ ...this.insertform });
              console.log('添加结果:', myjcs);
              if (myjcs.code == 1) {
                this.$message.success('添加成功！');


                // 只有当有文件需要上传时才执行上传操作
                if (this.fileList && this.fileList.length > 0) {
                  const formData = new FormData();

                  // 将文件添加到 FormData
                  this.fileList.forEach((file) => {
                    formData.append('images', file.raw); // file.raw 是原始文件
                  });

                  console.log('formData', formData);
                  formData.append('jcs_id', myjcs.data.insertId);
                  const r = await addPic(formData);
                  this.$message.success(r.msg);
                }

              } else {
                this.$message.error(`提交失败: ${myjcs.msg}`);
              }
            } catch (error) {
              console.error('提交出错:', error);
              this.$message.error('提交失败，请稍后再试');
            }

            this.insertNodeLoading = false;
            // this.getJcsList();

            // 关闭编辑节点窗口
            this.editDialogVisible = false;

            // 刷新树形图，重新绑定数据
            let res = await getJcs({ id: this.treeData.id });
            this.treeData = res.data;

            // 关闭插入子节点窗口
            this.insertDialogVisible = false;

          } else {
            this.$message.error('请填写完整信息');
            this.insertNodeLoading = false;
          }
        });


      } catch (e) {
        this.insertNodeLoading = false;
      }

    },
    // 编辑节点信息
    async editJcsNode() {
      try {

        // this.addLoading = true;
        // let rolesId=this.form.rolesId.join(",");
        await upJcsNode({ ...this.editForm });
        // this.addLoading = false;
        this.$message.success('修改成功！');
        // this.getJcsList();

        console.log('this.fileList.length', this.fileList.length);
        if (this.fileList.length > 0) {
          //  编辑图片
          const formData = new FormData();
          // 将文件添加到 FormData
          this.fileList.forEach((file) => {
            formData.append('images', file.raw); // file.raw 是原始文件
          });

          console.log('formData', formData);
          formData.append('jcs_id', this.editForm.id);
          const r = await addPic(formData);
          this.$message.success(r.msg);
          this.editDialogVisible = false;
        }
      } catch (e) {
        this.editNodeLoading = false;
      }

    },


    // 编辑根节点
    async edit() {
      try {

        this.addLoading = true;
        // let rolesId=this.form.rolesId.join(",");
        !this.form.id && await addJcs({ ...this.form });
        this.form.id && await upJcs({ ...this.form });
        this.addLoading = false;
        this.$message.success(this.form.id ? '修改成功！' : '添加成功！');
        this.getJcsList();
        this.dialogVisible = false;
      } catch (e) {
        this.addLoading = false;
      }

    },

    openDialog() {
      this.resetForm();
      this.dialogVisible = true;
      this.fileList = []
    },
    // 打开插入子节点的窗口
    openInsertDialog(id) {
      this.insertform = {is_leaf: 0,};
      this.insertform.parent_id = id;
      // 清空文件上传列表
      this.fileList = []
      this.insertDialogVisible = true;
    },
    async getRoles() {
      const { data } = await getRolesAll();
      this.rolesArr = data.map(t => { t.id = t.id.toString(); return t });
    },
    async getMoreAll() {
      const { data } = await getMoreAll();
      this.moreArr = data;
    },
    // 获取决策树列表，即根节点
    async getJcsList() {
      this.loading = true;
      const { data, total } = await getJcsList(this.queryParams);
      this.loading = false;
      this.jcsArr = data;
      this.total = total;
    },
    async getFalut() {
      const { data } = await getFaultList();
      this.faultArr = data;
    },
    async getAlarm() {
      const { data } = await getAlarmList();
      this.alarmArr = data;
    },

    handleQuery() {
      this.queryParams.page = 1;
      this.getJcsList();
    },


    // 图片操作
    // 预览图片
    handlePreview(file) {
      this.previewImage = file.url || file.raw;
      this.previewDialogVisible = true;
    },
    // 上传前校验
    beforeUpload(file) {
      // 文件大小限制为 2MB
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      // 允许 jpg/png 格式
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isImage) {
        this.$message.error('仅支持 JPG/PNG 格式!');
      }
      return isLt2M && isImage;
    },

    // 文件删除回调
    handleRemove(file, fileList) {
      this.fileList = fileList; // 更新文件列表
    },
    // 文件选择回调
    handleChange(file, fileList) {
      this.fileList = fileList; // 更新文件列表
    },








    // 决策树编辑窗口方法
    async clickNode(node) {
      // eslint-disable-next-line
      console.log(node);
      this.curNode = node;
      let nodedata = await getJcsNode({ id: node.id });
      console.log(nodedata);
      this.editForm = nodedata.data;
      this.imageList = nodedata.data.images;
      // 清空文件上传列表
      this.fileList = []
      this.editDialogVisible = true;
    },

    // 删除图片
    async deleteImage(img, index) {
      try {
        await delPic({ id: img.id });
        this.$message.success('删除图片成功');
        let nodedata = await getJcsNode({ id: this.editForm.id });
        this.editForm = nodedata.data;
        this.imageList = nodedata.data.images;
      } catch (error) {
        console.error('删除图片失败:', error, index);
        this.$message.error('删除图片失败');
      }
    }


  }
}
</script>
<style scoped lang="scss">
.boxs {
  padding: 20px;
}

.color-title {
  margin-bottom: 10px;
  color: #000;
}

.upload-demo {
  display: flex;
  flex-wrap: wrap;
}

.el-icon-plus {
  font-size: 32px;
  color: #8c939d;
}
</style>
